<?php

/**
 * Ajax_GetData.phtml - Edition d'un évènement
 *
 * @package
 * @author Alexis Eric
 * @copyright Copyright (c) 2012 - Erra Prod
 * @version $1.0$
 * @access public
 */
/**
 * import_rdv - Import de rendez-vous
 */
if ($GET_mode == 'import_rdv') {
    // Read file
    $READ_STEP = 50;
    $resultArray = array('position' => -1, 'message' => "Erreur lors de l'import du fichier");
    $file = $_POST['file_path'];
    $position = $_POST['position'];
    if (file_exists($file) && is_numeric($position)) {
        if (file_exists($file . '.cache')) {
            $stack = file_get_contents($file . '.cache');
            $stack = json_decode($stack, true);
        } else {
            $stack = ImportAction::getRdvImportArrayFromFile($file);
            file_put_contents(DOCUMENT_ROOT . '/public/__files/' . $file . '.cache', json_encode($stack));
        }
        $stack = array_reverse($stack);
        $inserted_rdv = 0;
        $realCount = count($stack);
        $errorList = '';
        if ($realCount > 1) {
            // On fait attention si on est dans la dernière itération
            if ($position + $READ_STEP > count($stack)) {
                $READ_STEP = count($stack) - $position;
            }
            if ($READ_STEP <= 0) {
                $resultArray['message'] = "L'import est terminé";
                $resultArray['position'] = -2;
            } else {
                $stack = array_slice($stack, $position, $READ_STEP);

                $prestaCorrespondanceArray = ImportAction::handlePrestas($stack);
                $agendaCorrespondanceArray = ImportAction::handleAgendas($stack);
                // Gestion de rendez-vous
                foreach ($stack as $index=>$rendezVous) {
                    if ($rendezVous[0] != 3600) { // On s'assure que la ligne en cours n'est pas un header
                        $insertRdv = array();
                        $insertRdv['object_class'] = 'Msa_SlotObject';
                        $insertRdv['agenda_id'] = $agendaCorrespondanceArray[trim($rendezVous[6])];
                        $insertRdv['prestation_id'] = $prestaCorrespondanceArray[trim($rendezVous[7])];
                        // Try to find client id
                        $clientId = Erra_Core_DatabasePdo::SELECT('SELECT id FROM msa_clientobject WHERE nom="' . $rendezVous[8] . '" AND prenom="' . $rendezVous[9] . '"');
                        if (is_numeric($insertRdv['prestation_id']) && is_numeric($insertRdv['agenda_id']) && Erra_Core_DatabasePdo::rowCount() && is_object($clientId)) {
                            $clientId = $clientId->fetch();
                            $clientId = $clientId->id;
                            $insertRdv['client_id'] = $clientId;
                            $insertRdv['slot_day'] = strtotime(date("Y-m-d", $rendezVous[0]));
                            $insertRdv['slot_start'] = $rendezVous[0] - $insertRdv['slot_day'];
                            $insertRdv['slot_end'] = ($rendezVous[1] - $rendezVous[0]) + $insertRdv['slot_start'];
                            $insertRdv['from_internet'] = isset($rendezVous[5]) ? $rendezVous[5] : 0;
                            $insertRdv['date_commande'] = $rendezVous[4];
                            $insertRdv['last_sync'] = $rendezVous[4];
                            $insertRdv['object_id'] = $insertRdv['event_id'] = uniqid();
                            $insertRdv['event_type'] = 'presta';
                            if ($rendezVous[3] == 'Pas Venu') {
                                $insertRdv['status_rdv'] = 'pas_venu';
                            } else if ($rendezVous[3] == 'Venu') {
                                $insertRdv['status_rdv'] = 'venu';
                            } else {
                                $insertRdv['status_rdv'] = 'en_attente';
                            }
                            // Check if rendez vous exists before insert
                            $rdvExists = Erra_Core_DatabasePdo::SELECT('SELECT id FROM msa_slotobject WHERE client_id="' . $clientId . '" AND prestation_id="' . $insertRdv['prestation_id'] . '" AND date_commande="' . $insertRdv['date_commande'] . '"');
                            
                            if (Erra_Core_DatabasePdo::rowCount() && is_object($rdvExists)) {
                                $errorList .= 'Le rendez-vous à la ligne '.($index+1+$position).' existe déja<br/>';
                            } else {
                                // Insertion du rendez-vous
                                $column_names = array_keys($insertRdv);
                                $column_values = ajax_sanitize_input_for_db_insert(array_values($insertRdv));
                                $request = 'INSERT INTO msa_slotobject(' . implode(', ', $column_names) . ') VALUES(' . implode(',', $column_values) . ')';
                                $result = Erra_Core_DatabasePdo::EXECUTE($request);
                                $inserted_rdv++;
                            }
                        }
                    } else {
                        $errorList .= 'La ligne '.($index+1+$position).' est mal formée<br/>';
                    }
                }
                // Mount back
                $newPrestas = count($prestaCorrespondanceArray);
                $newAgenda = count($agendaCorrespondanceArray);
                // Résultat
                $resultArray['position'] = $position + $READ_STEP;
                $resultArray['message'] = "<strong>Import de " . $READ_STEP . " éléments à partir de la ligne " . $resultArray['position'] . " sur un total de " . $realCount . "</strong>";
                $resultArray['message'] .= "<br/><br/><i>Etape précédente :";
                $resultArray['message'] .= "<br/>* $inserted_rdv rendez-vous inserés</i>";
                $resultArray['message'] .= "<br/>* " . ($READ_STEP - $inserted_rdv) . " non inserés (impossible de trouver avec certitude le client associé)</i>";
                $resultArray['extra_infos'] = $errorList;
                }
        }
    }
    echo json_encode($resultArray);
}


/**
 * import_clients - Import de clients
 */
if ($GET_mode == 'import_clients') {
    // Lecture du fichier
    $READ_STEP = 100;
    $resultArray = array('position' => -1, 'message' => "Erreur lors de l'import du fichier");
    $file = $_POST['file_path'];
    $position = $_POST['position'];
    if (file_exists($file) && is_numeric($position)) {
        if (file_exists($file)) {
            if (file_exists($file . '.cache')) {
                $stack = file_get_contents($file . '.cache');
                $stack = json_decode($stack, true);
            } else {
                // Si le cache est disponible, l'importer
                $stack = ImportAction::getRdvImportArrayFromFile($file);
                file_put_contents(DOCUMENT_ROOT . '/public/__files/' . $file . '.cache', json_encode($stack));
            }
            $stack = array_reverse($stack);
            if (count($stack) > 1) {
                // Prevent last iteration step
                if ($position + $READ_STEP > count($stack)) {
                    $READ_STEP = count($stack) - $position;
                }
                if ($READ_STEP <= 0) {
                    $resultArray['message'] = "L'import est terminé";
                    $resultArray['position'] = -2;
                } else {
                    $stack[0][2] = 'Né(e) le';
                    $stack[0][6] = 'Créé le';
                    // Prepare all data
                    $insertedRows = 0;
                    $updatedRows = 0;
                    for ($i = $position; $i < $position + $READ_STEP; $i++) {
                        $currentUser = $stack[$i];
                        if (isset($currentUser[0]) && isset($currentUser[1]) && isset($currentUser[6]) && is_numeric(trim($currentUser[6]))) {
                            $database_insert = array();
                            $database_insert['nom'] = ucfirst(strtolower(trim($currentUser[0])));
                            $database_insert['prenom'] = ucfirst(strtolower(trim($currentUser[1])));
                            $database_insert['date_creation'] = trim($currentUser[7]);
                            $database_insert['object_class'] = 'Msa_ClientObject';
                            // Optional user infos
                            if (isset($currentUser[5]) && strlen($currentUser[5])) {
                                $database_insert['email'] = trim($currentUser[5]);
                            }
                            if (isset($currentUser[7]) && strlen($currentUser[7])) {
                                $database_insert['adresse'] = trim($currentUser[7]);
                            }
                            if (isset($currentUser[3]) && strlen($currentUser[3])) {
                                $database_insert['telephone_portable'] = trim($currentUser[3]);
                            }
                            if (isset($currentUser[4]) && strlen($currentUser[4])) {
                                $database_insert['telephone_fixe'] = trim($currentUser[4]);
                            }
                            if (isset($currentUser[9]) && strlen($currentUser[9])) {
                                $database_insert['code_postal'] = trim($currentUser[9]);
                            }
                            if (isset($currentUser[8]) && strlen($currentUser[8])) {
                                $database_insert['ville'] = trim($currentUser[8]);
                            }
                            // Check if user exists
                            $userExists = Erra_Core_DatabasePdo::SELECT('SELECT object_id FROM msa_clientobject WHERE date_creation="' . $database_insert['date_creation'] . '" AND nom="' . $database_insert['nom'] . '" AND prenom="' . $database_insert['prenom'] . '"');
                            // From an external source, creation date should be a sufficient key
                            if (Erra_Core_DatabasePdo::rowCount() && is_object($userExists)) {
                                // Update
                                $userExists = $userExists->fetch();
                                $database_insert['object_id'] = $userExists->object_id;
                                $database_insert['client_internet'] = 0;
                                $column_names = array_keys($database_insert);
                                $column_values = ajax_sanitize_input_for_db_insert(array_values($database_insert));
                                $request = 'UPDATE msa_clientobject SET ';
                                foreach ($column_names as $key => $column_name) {
                                    $request .= $column_name.='=' . $column_values[$key];
                                    if ($key <= (count($column_names) - 2)) {
                                        $request .= ', ';
                                    }
                                }
                                $request .= ' WHERE object_id="' . $database_insert['object_id'] . '"';
                                $result = Erra_Core_DatabasePdo::EXECUTE($request);
                                $updatedRows++;
                            } else {
                                // Insert
                                $database_insert['object_id'] = uniqid();
                                $database_insert['client_internet'] = 0;
                                $column_names = array_keys($database_insert);
                                $column_values = ajax_sanitize_input_for_db_insert(array_values($database_insert));
                                $request = 'INSERT INTO msa_clientobject(' . implode(', ', $column_names) . ') VALUES(' . implode(',', $column_values) . ')';
                                $result = Erra_Core_DatabasePdo::EXECUTE($request);
                                $insertedRows++;
                            }
                        }
                    }
                    // end for loop
                    $badForm = $READ_STEP - ($updatedRows + $insertedRows) >= 0 ? $READ_STEP - ($updatedRows + $insertedRows) : 0;
                    $resultArray['position'] = $position + $READ_STEP;
                    $resultArray['message'] = "<strong>Import de " . $READ_STEP . " éléments à partir de la ligne " . $resultArray['position'] . " sur un total de " . count($stack) . "</strong>";
                    $resultArray['message'] .= "<br/><br/><i>Etape précédente :";
                    $resultArray['message'] .= "<br/>* $insertedRows  insertion(s) ";
                    $resultArray['message'] .= "<br/>* $updatedRows  mise(s) à jour ";
                    $resultArray['message'] .= "<br/>* $badForm  enregistrement(s) mal formés</i>";
                }
            }
        }
    }
    echo json_encode($resultArray);
}


/**
 * check_conflicts - Gestion des conflits lors de la suppression d'un élément
 */
if ($GET_mode == 'check_conflicts') {
    $data_object = $_POST['data_object'];
    $element_id = str_replace('dialogDeleteConfirm_', '', $_POST['element_id']);
    $res = '';
    if (strlen($data_object) && ctype_alnum($element_id)) {
        if ($data_object == 'msa_prestationobject') {
            // Find feature prestations
            $presta_id = Erra_Core_DatabasePdo::SELECT('SELECT id FROM msa_prestationobject WHERE object_id="' . $element_id . '"');
            if (Erra_Core_DatabasePdo::rowCount()) {

                $presta_id = $presta_id->fetch();
                $presta_id = $presta_id->id;
                if ($presta_id == 0) {
                    echo 'FORBIDDEN';
                } else {
                    $getCount = Erra_Core_DatabasePdo::SELECT('SELECT COUNT(id) AS num_future, (SELECT COUNT(id) FROM msa_slotobject WHERE prestation_id=' . $presta_id . ') AS num_total FROM msa_slotobject WHERE prestation_id=' . $presta_id . ' AND (slot_day+slot_start) > ' . time());

                    if (is_object($getCount)) {
                        $getCount = $getCount->fetch();
                        $num_future = $getCount->num_future;
                        $num_total = $getCount->num_total;
                        $res .= 'Etes vous sur de vouloir supprimer cet élément ?<br/><br/>';
                        if ($num_future > 0) {
                            $res .= 'Il existe <font color="red">' . $num_future . ' rendez-vous futur(s)</font> utilisant cette prestation.<br/>';
                        }
                        if ($num_total > 0) {
                            $res .= 'Il y au total ' . $num_total . ' rendez-vous utilisant cette prestation.<br/><br/>';
                            $res .= '<font color="red"><strong>La supprimer supprimera également les rendez-vous associés</strong></font><br/>';
                        }
                        echo $res;
                    }
                }
            }
        } else if ($data_object == 'msa_clientobject') {
            // Find feature prestations
            $client_id = Erra_Core_DatabasePdo::SELECT('SELECT id FROM msa_clientobject WHERE object_id="' . $element_id . '"');
            if (Erra_Core_DatabasePdo::rowCount()) {
                $client_id = $client_id->fetch();
                $client_id = $client_id->id;

                $getCount = Erra_Core_DatabasePdo::SELECT('SELECT COUNT(id) AS num_future, (SELECT COUNT(id) FROM msa_slotobject WHERE client_id=' . $client_id . ') AS num_total FROM msa_slotobject WHERE client_id=' . $client_id . ' AND (slot_day+slot_start) > ' . time());
  
                if (is_object($getCount)) {
                    $getCount = $getCount->fetch();
                    $num_future = $getCount->num_future;
                    $num_total = $getCount->num_total;
                    $res .= 'Etes vous sur de vouloir supprimer cet élément ?<br/><br/>';
                    if ($num_future > 0) {
                        $res .= 'Il existe <font color="red">' . $num_future . ' rendez-vous futur(s)</font> pour ce client.<br/>';
                    } 
                    if ($num_total > 0) {
                        $res .= 'Il y au total ' . $num_total . ' rendez-vous pour ce client.<br/><br/>';
                        $res .= '<font color="red"><strong>Le supprimer supprimera également les rendez-vous associés</strong></font><br/>';
                    }
                    echo $res;
                }
            }
        } else if ($data_object == 'msa_agendaobject') {
            // Find feature prestations
            $agenda_id = Erra_Core_DatabasePdo::SELECT('SELECT id FROM msa_agendaobject WHERE object_id="' . $element_id . '"');
            if (Erra_Core_DatabasePdo::rowCount()) {
                $agenda_id = $agenda_id->fetch();
                $agenda_id = $agenda_id->id;
                $getCount = Erra_Core_DatabasePdo::SELECT('SELECT COUNT(id) AS num_future, (SELECT COUNT(id) FROM msa_slotobject WHERE agenda_id=' . $agenda_id . ') AS num_total FROM msa_slotobject WHERE agenda_id=' . $agenda_id . ' AND (slot_day+slot_start) > ' . time());

                if (is_object($getCount)) {
                    $getCount = $getCount->fetch();
                    $num_future = $getCount->num_future;
                    $num_total = $getCount->num_total;
                    $res .= 'Etes vous sur de vouloir supprimer cet élément ?<br/><br/>';
                    if ($num_future > 0) {
                        $res .= 'Il existe <font color="red">' . $num_future . ' rendez-vous futur(s)</font> pour cet agenda.<br/>';
                    }
                    if ($num_total > 0) {
                        $res .= 'Il y au total ' . $num_total . ' rendez-vous pour cet agenda.<br/><br/>';
                        $res .= '<font color="red"><strong>Le supprimer supprimera également les rendez-vous associés</strong></font><br/>';
                    }
                    echo $res;
                }
            }
        } else if ($data_object == 'msa_typeprestationobject') {
            // Find feature prestations
            $type_prestation_id = Erra_Core_DatabasePdo::SELECT('SELECT id FROM msa_typeprestationobject WHERE object_id="' . $element_id . '"');
            if (Erra_Core_DatabasePdo::rowCount()) {
                $type_prestation_id = $type_prestation_id->fetch();
                $type_prestation_id = $type_prestation_id->id;
                if ($type_prestation_id == 0) {
                    echo 'FORBIDDEN';
                } else {
                    $num_used = Erra_Core_DatabasePdo::SELECT('SELECT COUNT(id) AS num_used FROM msa_prestationobject WHERE prestation_type_id=' . $type_prestation_id);

                    if (is_object($num_used)) {
                        $num_used = $num_used->fetch();
                        $num_used = $num_used->num_used;
                        if ($num_used > 0) {
                            echo 'Etes vous sur de vouloir supprimer cette catégorie ?<br/><br/>';
                            echo '<strong>Il existe ' . $num_used . ' prestations qui utilisent cette catégorie</strong><br/><br/>';
                            echo '<strong><font color="red">La supprimer supprimera également les prestations associés et les rendez-vous associés à cette catégorie !!!</font></strong>';
                        }
                    }
                }
            }
        }
    }
}


/**
 * create_client - Création d'un client
 */
if ($GET_mode == 'create_client') {
    $stackClientIdToDbId = array();
    foreach ($_POST['CREATE_CLIENT'] as $CREATE_CLIENT) {
        foreach ($CREATE_CLIENT as $element) {
            $createClientData[$element['name']] = $element['value'];
        }
        $create_client_id = $createClientData['create_client_id'];
        $createClientData['object_class'] = 'Msa_ClientObject';
        $createClientData['object_id'] = $create_client_id;
        unset($createClientData['create_client_id']);
        $column_names = array_keys($createClientData);
        $column_values = ajax_sanitize_input_for_db_insert(array_values($createClientData));
        $request = 'INSERT INTO msa_clientobject(' . implode(', ', $column_names) . ') VALUES(' . implode(', ', $column_values) . ')';
        $result = Erra_Core_DatabasePdo::EXECUTE($request);
        $lastId = Erra_Core_DatabasePdo::SELECT("SELECT id FROM msa_clientobject ORDER BY id DESC LIMIT 1")->fetch();
        $stackClientIdToDbId[(string) $create_client_id] = $lastId->id;
    }
    echo json_encode($stackClientIdToDbId);
}

/**
 * update_to - Mise à jour
 */
if ($GET_mode == 'update_to') {
    if (isset($_POST['update_target']) && is_numeric($_POST['update_target'])) {
        // Get files
        ob_start();
        post_curl(config_get('root_server') . '/json/get_update_version', array('update_target' => $_POST['update_target']));
        $update_contents = ob_get_contents();
        ob_end_clean();
        $update_contents = json_decode($update_contents, true);
        $update_version = $_POST['update_target'];
        // L'update est autorisé ?
        /////////////////////////
        $isDebugUpdateAndAllowed = ($update_version[3] == 5 && config_get('allow_debug_updates'));
        $isDebugUpdateForcedAndAllowed = ($update_version[3] == 7 && config_get('allow_debug_updates'));
        $isNotInternalUpdate = ($update_version[3] != 5);
        $isNotForcedVersion = ($update_version[3] != 6);
        // Mettre à jour si autorisé
        //////////////////////////
        if ($isDebugUpdateAndAllowed || $isDebugUpdateForcedAndAllowed || ($isNotInternalUpdate && $isNotForcedVersion)) {
            if (is_array($update_contents) && isset($update_contents['update.data']) && strlen($update_contents['update.data'])) {
                $fileList = explode(',', $update_contents['update.data']);
                if (is_array($fileList) && count($fileList)) {
                    $fileCount = count($fileList);
                    $positive = 0;
                    foreach ($fileList as $updateFile) {
                        $updateFile = trim($updateFile);
                        if (isset($update_contents[$updateFile]) && strlen($update_contents[$updateFile])) {
                            $res = eval($update_contents[$updateFile]);
                            if ($res !== FALSE) {
                                $positive++;
                            }
                        }
                    }
                    if ($positive > 0) {
                        $text = "La mise à jour a été  effectuée (" . $positive . ' fichiers sur ' . $fileCount . ' mis à jour)';
                        if (is_array($update_contents) && isset($update_contents['description.txt'])) {
                            $text .= '<br/><br/>' . nl2br($update_contents['description.txt']);
                            Erra_Core_DatabasePdo::EXECUTE('UPDATE config_generalconfigobject SET version="' . $_POST['update_target'] . '"');
                        }
                    } else {
                        $text = "La mise à jour n'a pas pu être effectuée";
                    }
                }
            }
        }

        $text = (strlen($text)) ? $text : "Une erreur est survenue lors de la mise à jour !";
        echo Erra_Utils_Rest::Code_200_OK($text);
    } else {
        echo Erra_Utils_Rest::Code_304_Not_Modified("Aucune mise à jour n'a été effectuée");
    }
}

/**
 * restore_rdv - Restauration d'un rendez-vous depuis la corbeille
 */
if ($GET_mode == 'restore_rdv') {
    if (isset($_POST['event_id']) && ctype_alnum($_POST['event_id'])) {
        $event_id = $_POST['event_id'];
        Erra_Core_DatabasePdo::EXECUTE('INSERT INTO msa_slotobject (SELECT * FROM msa_slotobjecttrash WHERE object_id="' . $event_id . '")');
        Erra_Core_DatabasePdo::EXECUTE('UPDATE msa_slotobject SET object_class="Msa_SlotObject" WHERE object_id="' . $event_id . '"');
        Erra_Core_DatabasePdo::EXECUTE('DELETE FROM msa_slotobjecttrash WHERE object_id="' . $event_id . '"');
        echo Erra_Utils_Rest::Code_200_OK("L'évènement a été correctement restauré");
    } else {
        echo Erra_Utils_Rest::Code_400_Bad_Request("Erreur dans la requête, impossible de supprimer cet évènement");
    }
}

/**
 * templated_mail - Envoyer un mail templaté
 */
if ($GET_mode == 'templated_mail') {
    if (isset($_POST['event_id']) && ctype_alnum($_POST['event_id'])) {
        $event_id = $_POST['event_id'];
        $originSlots = Erra_Core_DatabasePdo::SELECT('SELECT slot_day, slot_start, slot_end FROM msa_slotobject WHERE msa_slotobject.event_id ="' . $event_id . '"');
        if (is_object($originSlots)) {
            $originSlots = $originSlots->fetch();
        }
        $rdv = Erra_Core_DatabasePdo::SELECT('SELECT msa_agendaobject.email AS presta_email, msa_agendaobject.telephone_portable AS presta_portable, slot_day, slot_start, nom, prenom, msa_clientobject.email AS user_mail, msa_clientobject.telephone_portable AS user_portable FROM msa_slotobject, msa_clientobject, msa_agendaobject WHERE msa_slotobject.event_id ="' . $event_id . '" AND msa_clientobject.id=msa_slotobject.client_id AND msa_agendaobject.id=msa_slotobject.agenda_id');
        if (is_object($rdv) && is_object($originSlots)) {
            // Edition d'un rendez-vous
            $rdv = $rdv->fetch();
            // Get placeholders
            $nom_complet = $rdv->nom . ' ' . $rdv->prenom;
            $date_reservation = date('d/m/Y', $rdv->slot_day);
            $heure_reservation = time_to_str_hour($rdv->slot_start);
            $nom_etablissement = Config_GeneralConfigObject::get('nom_etablissement');
            $nouvelle_date_reservation = date('d/m/Y', $rdv->slot_day);
            $nouvelle_heure_reservation = time_to_str_hour($rdv->slot_start);
            $placeHolders = array('{nom_complet}' => $nom_complet,
                '{date_reservation}' => $date_reservation,
                '{heure_reservation}' => $heure_reservation,
                '{nom_etablissement}' => $nom_etablissement,
                '{nouvelle_date_reservation}' => $nouvelle_date_reservation,
                '{nouvelle_heure_reservation}' => $nouvelle_heure_reservation);

            if ($_POST['function'] == 'internal') {
                if (strlen($rdv->user_portable)) {
                    $result = Erra_Utils_Tools::sendTemplatedSms($rdv->user_portable, 'Mail/Sms_RdvEditClient.phtml', $placeHolders);
                }
                $result = Erra_Utils_Tools::sendTemplatedMail($rdv->user_mail, 'Mail/Mail_RdvEditClientInternal.phtml', $placeHolders);
                $presta_mail = strlen($rdv->presta_email) ? $rdv->presta_email : '';
                if (strlen($presta_mail)) {
                    $result = Erra_Utils_Tools::sendTemplatedMail($presta_mail, 'Mail/Mail_RdvEdit.phtml', $placeHolders);
                }
            } else if ($_POST['function'] == 'client') {
                $result = Erra_Utils_Tools::sendTemplatedMail($rdv->user_mail, 'Mail/Mail_RdvEditClient.phtml', $placeHolders);

                $presta_mail = strlen($rdv->presta_email) ? $rdv->presta_email : '';
                if (strlen($presta_mail)) {
                    $result = Erra_Utils_Tools::sendTemplatedMail($presta_mail, 'Mail/Mail_RdvEdit.phtml', $placeHolders);
                }
            }
        }
    }
    echo Erra_Utils_Rest::Code_200_OK("Le mail a corretement été envoyé");
}

/**
 * purge_data - Nettoyer les rendez-vous antérieurs à 3 mois
 */
if ($GET_mode == 'purge_data') {
    if (isset($_POST['magic']) && $_POST['magic'] == 'purge_data') {
        $nbRdvQuery = Erra_Core_DatabasePdo::SELECT('SELECT COUNT(id) AS num_rdv FROM `msa_slotobject` WHERE slot_day < (' . time() . ' - 90*3600*24)');
        if (Erra_Core_DatabasePdo::rowCount()) {
            $nbRdvQuery = $nbRdvQuery->fetch();
            Erra_Core_DatabasePdo::EXECUTE('DELETE FROM `msa_slotobject` WHERE slot_day < (' . time() . ' - 90*3600*24)');
            echo Erra_Utils_Rest::Code_200_OK($nbRdvQuery->num_rdv . ' rendez-vous ont été supprimés');
        } else {
            echo Erra_Utils_Rest::Code_200_OK("Aucun rendez-vous à supprimer");
        }
    } else {
        echo Erra_Utils_Rest::Code_400_Bad_Request("Erreur dans la requête");
    }
}

/*
 * google_synchronize - Synchronisation avec google calendar
 */
if ($GET_mode == 'google_synchronize') {
    if (isset($_POST['login']) && isset($_POST['password'])) {
        $login = $_POST['login'];
        $password = $_POST['password'];
        $agenda_google = $_POST['agenda_google'];
        $google_agenda_id = $_POST['google_agenda_id'];
        if (!strlen($login) && !strlen($password)) {
            Tools_GCalendarObject::saveGoogleAccess('', '');
            echo Erra_Utils_Rest::Code_200_OK("La synchronisation avec Google est desactivée");
        } else {
            if (!strlen($password)) {
                $password = Config_ConfigObject::get('pwd_google');
                if (strlen($password)) {
                    $password = __decrypt($password);
                }
            }
            Tools_GCalendarObject::checkLogin($login, $password, $agenda_google, $google_agenda_id);
        }
    }
}

/**
 * count_masssms - Calcul du cout des SMS
 */
if ($GET_mode == 'count_masssms') {
    if (isset($_POST['news_id']) && is_numeric($_POST['news_id'])) {
        $id = $_POST['news_id'];
        $select = Erra_Core_DatabasePdo::SELECT('SELECT * FROM msa_campaignsmsobject WHERE id=' . $id);
        if (Erra_Core_DatabasePdo::rowCount()) {
            $result = $select->fetch();
            $shop_target = (is_numeric($result->shop_target)) ? ' AND location=' . $result->shop_target . ' ' : '';
            $userList = Erra_Core_DatabasePdo::SELECT('SELECT msa_clientobject.telephone_portable, client_id, location FROM msa_clientobject, msa_slotobject, msa_agendaobject WHERE msa_slotobject.agenda_id=msa_agendaobject.id  AND client_id=msa_clientobject.id ' . $shop_target . ' GROUP BY client_id');

            if (Erra_Core_DatabasePdo::rowCount()) {
                $userPhone = array();
                while ($row = $userList->fetch()) {
                    if (is_numeric($row->client_id) && strlen($row->telephone_portable)) {
                        $userPhone[] = $row->telephone_portable;
                    }
                }
                if (count($userPhone)) {
                    $nbSms = count($userPhone);
                    $smsPrice = '';
                    if (isset($_POST['sms_cost']) && is_numeric($_POST['sms_cost'])) {
                        $smsCost = $_POST['sms_cost'];
                        $smsPrice .= '<br/>Cette campagne vous coutera ' . number_format((float) $smsCost * $nbSms, 2) . ' € (' . $smsCost . ' € par SMS';
                    }
                    echo 'Cette campagne nécessite l{envoi de ' . $nbSms . ' SMS' . $smsPrice;
                } else {
                    echo 'Aucun SMS à envoyer';
                }
            }
        }
    }
}

/**
 * send_masssms - Envoi des SMS en masse
 */
if ($GET_mode == 'send_masssms') {
    if (isset($_POST['news_id']) && is_numeric($_POST['news_id'])) {
        $id = $_POST['news_id'];
        $date_envoi = time();
        Erra_Core_DatabasePdo::EXECUTE('UPDATE msa_campaignsmsobject SET date_envoi="' . $date_envoi . '"');
        // Envoi en masse
        $select = Erra_Core_DatabasePdo::SELECT('SELECT * FROM msa_campaignsmsobject WHERE id=' . $id);
        if (Erra_Core_DatabasePdo::rowCount()) {
            $result = $select->fetch();
            $message = $result->content_campaign;
            $shop_target = (is_numeric($result->shop_target)) ? ' AND location=' . $result->shop_target . ' ' : '';
            $userList = Erra_Core_DatabasePdo::SELECT('SELECT msa_clientobject.telephone_portable, client_id, location FROM msa_clientobject, msa_slotobject, msa_agendaobject WHERE msa_slotobject.agenda_id=msa_agendaobject.id  AND client_id=msa_clientobject.id ' . $shop_target . ' GROUP BY client_id');
            if (Erra_Core_DatabasePdo::rowCount()) {
                $userPhone = array();
                while ($row = $userList->fetch()) {
                    if (is_numeric($row->client_id) && strlen($row->telephone_portable)) {
                        $userPhone[] = $row->telephone_portable;
                    }
                }
                if (count($userPhone)) {
                    $countPhones = count($userPhone);
                    $result = Erra_Utils_Tools::sendMassSms($userPhone, $message);
                    $heure = date('G', $date_envoi) . 'h' . date('i', $date_envoi);

                    echo '<strong><font color="green">Dernier envoi : ' . date('d/m/Y', $date_envoi) . ' à ' . $heure . '</font></strong><br/>';
                    $successCount = $countPhones - 0;
                    $failCount = 0;
                    echo $successCount . ' succès, ' . $failCount . ' echec(s)';
                } else {
                    echo '<strong><font color="orange">Aucun SMS à envoyer</font></strong>';
                }
            }
        }
    }
}

/**
 * send_newsletter - Envoi de la newsletter
 */
if ($GET_mode == 'send_newsletter') {
    if (isset($_POST['news_id']) && is_numeric($_POST['news_id'])) {
        $id = $_POST['news_id'];
        $date_envoi = time();
        Erra_Core_DatabasePdo::EXECUTE('UPDATE msa_campaignmailobject SET date_envoi="' . $date_envoi . '"');
        // MASS SEND
        $select = Erra_Core_DatabasePdo::SELECT('SELECT * FROM msa_campaignmailobject WHERE id=' . $id);
        if (Erra_Core_DatabasePdo::rowCount()) {
            $result = $select->fetch();
            $title = $result->title;
            $message = $result->content_campaign;
            $shop_target = (is_numeric($result->shop_target)) ? ' AND location=' . $result->shop_target . ' ' : '';
            $userList = Erra_Core_DatabasePdo::SELECT('SELECT msa_clientobject.email, client_id, location FROM msa_clientobject, msa_slotobject, msa_agendaobject WHERE msa_slotobject.agenda_id=msa_agendaobject.id  AND client_id=msa_clientobject.id ' . $shop_target . ' GROUP BY client_id');
            if (Erra_Core_DatabasePdo::rowCount()) {
                $userMail = array();
                while ($row = $userList->fetch()) {
                    if (is_numeric($row->client_id)) {
                        $userMail[] = $row->email;
                    }
                }
                if (count($userMail)) {
                    $countMails = count($userMail);
                    $result = Erra_Utils_Tools::sendMassMail($userMail, $title, $message, $_POST['news_id']);
                    $heure = date('G', $date_envoi) . 'h' . date('i', $date_envoi);

                    echo '<strong><font color="green">Dernier envoi : ' . date('d/m/Y', $date_envoi) . ' à ' . $heure . '</font></strong><br/>';
                    $successCount = $countMails - $result;
                    $failCount = $result;
                    echo $successCount . ' succès, ' . $failCount . ' echec(s)';
                } else {
                    echo '<strong><font color="orange">Aucun e-mail à envoyer</font></strong>';
                }
            }
        }
    }
}

/**
 * delete_img - Suppression d'une image
 */
if ($GET_mode == 'delete_img') {
    if (strlen($_POST['delete_src'])) {
        $src = $_POST['delete_src'];
        $src_mini = explode('/', $src);
        $src_mini[count($src_mini) - 1] = 'mini-' . $src_mini[count($src_mini) - 1];
        $src_mini = implode('/', $src_mini);
        $src = trim($src, '/');
        $src_mini = trim($src_mini, '/');
        $src = DOCUMENT_ROOT . '/public/__files/' . $src;
        $src_mini = DOCUMENT_ROOT . '/public/__files/' . $src_mini;
        if (file_exists($src) && file_exists($src_mini)) {
            unlink($src);
            unlink($src_mini);
            echo '200';
        }
    }
}

/**
 * client_list - Affichage AJAX d'une liste de clients
 */
if ($GET_mode == 'client_list') {
    $resultArray = array();
    $term = urldecode(str_replace('term=', '', $_SERVER['QUERY_STRING']));
    $request = strip_non_alnum($term);
    $result = Erra_Core_DatabasePdo::SELECT('SELECT * FROM msa_clientobject WHERE nom LIKE "' . $request . '%" OR prenom LIKE "' . $request . '%"');

    // Add Found Clients
    if (Erra_Core_DatabasePdo::rowCount()) {
        while ($row = $result->fetch()) {
            $resultArray[] = array('label' => $row->nom . ' ' . $row->prenom, 'value' => $row->id);
        }
    }

    echo json_encode($resultArray);
}

/**
 * client_list_uniqid - Gestion d'une liste de clients
 */
if ($GET_mode == 'client_list_uniqid') {
    $resultArray = array();
    $term = urldecode(str_replace('term=', '', $_SERVER['QUERY_STRING']));
    $request = strip_non_alnum($term); // FIXME : sanitize better to avoid injections
    $result = Erra_Core_DatabasePdo::SELECT('SELECT * FROM msa_clientobject WHERE nom LIKE "' . $request . '%" OR prenom LIKE "' . $request . '%"');

    // Add Found Clients
    if (Erra_Core_DatabasePdo::rowCount()) {
        while ($row = $result->fetch()) {
            $resultArray[] = array('label' => $row->nom . ' ' . $row->prenom, 'value' => $row->object_id);
        }
    }

    echo json_encode($resultArray);
}

/**
 * create_ajax_user - Créér un utilisateur en AJAX
 */
if ($GET_mode == 'create_ajax_user') {
    $post = $_POST;
    $post['object_class'] = 'Msa_ClientObject';
    $post['object_id'] = uniqid();
    $column_names = array_keys($post);
    $column_values = ajax_sanitize_input_for_db_insert(array_values($post));
    $request = 'INSERT INTO msa_clientobject(' . implode(', ', $column_names) . ') VALUES(' . implode(', ', $column_values) . ')';
    $result = Erra_Core_DatabasePdo::EXECUTE($request);
    $lastId = Erra_Core_DatabasePdo::SELECT("SELECT id FROM msa_clientobject ORDER BY id DESC LIMIT 1")->fetch();
    $inserted_id = $lastId->id;
    if ($inserted_id > 0) {
        echo $inserted_id;
    } else {
        echo 'fail';
    }
}

/**
 * edit_ajax_user - Edition d'un utilisateur en AJAX
 */
if ($GET_mode == 'edit_ajax_user') {
    $post = $_POST;
    $user_id = -1;
    if (isset($post['edit_user_id']) && is_numeric($post['edit_user_id'])) {
        $user_id = $post['edit_user_id'];
        unset($post['edit_user_id']);
    }
    if ($user_id > -1) {
        $column_names = array_keys($post);
        $column_values = ajax_sanitize_input_for_db_insert(array_values($post));

        foreach ($column_names as $i => $column_name) {
            $request[] = $column_name . ' = ' . $column_values[$i];
        }
        $request = 'UPDATE Msa_ClientObject SET ' . implode(', ', $request) . ' WHERE id = ' . $user_id;
        $result = Erra_Core_DatabasePdo::EXECUTE($request);
    }

    if (is_numeric($user_id)) {
        echo $user_id;
    } else {
        echo 'fail';
    }
}

/**
 * check_user_email - Vérifie si un utilisateur existe
 */
if ($GET_mode == 'check_user_email') {
    $post = $_POST;
    if (isset($post['email']) && strlen($post['email'])) {
        // Check if email exists
        Erra_Core_DatabasePdo::SELECT('SELECT id FROM msa_clientobject WHERE email = "' . $post['email'] . '"');
        if (Erra_Core_DatabasePdo::rowCount()) {
            echo Erra_Utils_Rest::Code_306_Reserved('L\'adresse e-mail existe déja');
        } else {
            echo Erra_Utils_Rest::Code_200_OK();
        }
    }
}

/**
 * fiche_client - Gestion d'une fiche client
 */
if ($GET_mode == 'fiche_client') {
    $post = $_POST;
    $res = '';
    if (isset($post['client_id']) && is_numeric($post['client_id'])) {
        // Get client infos
        $clientRequest = Erra_Core_DatabasePdo::SELECT('SELECT * FROM msa_clientobject WHERE id=' . $post['client_id']);
        if (Erra_Core_DatabasePdo::rowCount()) {
            $client = $clientRequest->fetch();

            $res .= '<center>';
            $res .= '<div class="fiche-client-title">' . ucfirst($client->civilite) . ' ' . ucfirst(strtolower($client->nom)) . ' ' . ucfirst(strtolower($client->prenom)) . '</div>';
            $res .= '<img src="' . config_get('public_images') . '/ui/client.png" width=25 height=25>';
            $res .= '</center>';
            $res .= '<div class="fiche-client-left-infos">';
            $res .= '<p>Informations</p>';
            if (strlen($client->adresse)) {
                $res .= '<br/> Adresse : <span class="fiche-client-address">' . $client->adresse . '</span>';
            }
            if (strlen($client->telephone_portable)) {
                $res .= '<br/> Téléphone portable : <span class="fiche-client-phone">' . $client->telephone_portable . '</span>';
            }
            if (strlen($client->email)) {
                $res .= '<br/> Mail : ' . $client->email;
            }
            $res .= '</div>';
        }
    }
    $res = strlen($res) ? $res : 'Impossible de remonter les informations sur ce client !';
    echo $res;
}

/**
 * sync_google_calendar - Synchronisation du google calendar
 */
if ($GET_mode == 'sync_google_calendar') {
    $event_id = $_POST['event_id'];
    $action = $_POST['action'];
    if (ctype_alnum($event_id) && ctype_alnum($action)) {
        if ($action == 'create') {
            Tools_GCalendarObject::addEventFromUniqId($event_id);
        } else if ($action == 'delete') {
            Tools_GCalendarObject::deleteEventFromUniqid($event_id);
        } else if ($action == 'edit') {
            //Tools_GCalendarObject::deleteEventFromUniqid($event_id);
            ///Tools_GCalendarObject::addEventFromUniqId($event_id); 
            Tools_GCalendarObject::editEventFromUniqId($event_id);
        }
        echo 200;
    }
}
?>